<template>
  <div class="pageWrapper" style="min-height: 600px;height: auto">
    <row class="form">
      <SearchBar
        @onSearch="handleAccountChecking"
        :showClear="false"
        :searchBtnText="searchBtnText"
        :searchBtn="disabledSearchBtn"
      >
        <SearchBarItem label="实际清算日期：" :labelLg="8">
          <DatePicker
            type="date"
            format="yyyy-MM-dd"
            :clearable="false"
            v-model="searchModule.actualClearDate"
            @on-change="handleChange"
          ></DatePicker>
        </SearchBarItem>
        <SearchBarItem label="商户：" :labelLg="8">
          <Select
            filterable
            clearable
            v-model="searchModule.merchantCode"
            placeholder="请选择"
            @on-change="handleChange"
          >
            <Option
              :value="item.value"
              v-for="(item, value) in tenants"
              :key="value"
              >{{ item.label }}</Option
            >
          </Select>
        </SearchBarItem>
        <SearchBarItem label="渠道：" :labelLg="8">
          <Select
            filterable
            v-model="searchModule.payChannel"
            placeholder="请选择"
            @on-change="handleChange"
          >
            <Option
              :value="item.key"
              v-for="(item, key) in channels"
              :key="key"
              >{{ item.value }}</Option
            >
          </Select>
        </SearchBarItem>
      </SearchBar>
    </row>
    <Row class="form">
      <Col>
        <Authc permissions="trade:settlement:settleManage:funds:export">
          <Button type="primary" @click="exportOne" :disabled="disabledSearchBtn"
            >导出</Button
          >
        </Authc>
        <Authc permissions="trade:settlement:settleManage:funds:update">
          <Button
            type="error"
            :ghost="true"
            :disabled="isNormal"
            @click="doReSettle"
            >更新</Button
          >
        </Authc>
        <Authc permissions="trade:settlement:settleManage:funds:exportAll">
          <Button @click="handleShowCollectExport">汇总导出</Button>
        </Authc>
      </Col>
    </Row>
    <Card
      title="正常对账数据"
      v-if="
        this.settleSummary != null &&
        this.settleSummary != {} &&
        this.settleSummary.id
      "
    >
      <NormalForm :iconStyle="iconStyle" :settleSummary="settleSummary" />
    </Card>
    <Card
      class="card"
      title="异常对账数据"
      v-if="
        this.settleSummary != null &&
        this.settleSummary != {} &&
        this.settleSummary.id
      "
    >
      <AbnormalForm
        :diffCauseList="diffCauseList"
        :namespace="namespace"
        :settleSummary="settleSummary"
      />
    </Card>
    <Modal
      v-model="showCollectExport"
      title="汇总导出"
      @on-ok="collectExport"
      ok-text="导出"
      width="400px"
    >
      <Row class="form">
        <RadioGroup v-model="exportDateType" type="button">
          <Radio label="date">按日</Radio>
          <Radio label="month">按月</Radio>
        </RadioGroup>
        <DatePicker
          :type="exportDateType"
          :clearable="false"
          :format="exportDateType == 'date' ? 'yyyy年MM月dd日' : 'yyyy年MM月'"
          v-model="exportDate"
        ></DatePicker>
      </Row>
    </Modal>
  </div>
</template>

<script>
import {
  Input,
  DatePicker,
  Button,
  Message,
  Select,
  Option,
  Row,
  Col,
  Card,
  Modal,
  RadioGroup,
  Radio,
} from "view-design";
import SearchBar from "@/components/SearchBar";
import { namespace } from "../Module/accountCheckingModule";
import { AbnormalForm, NormalForm } from "./AccountForm";
import util from "../../../../../utils/util";
import Authc from "@/components/Authc";

export default {
  name: "account_checking",
  components: {
    Input,
    Button,
    DatePicker,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    Message,
    Select,
    Option,
    Row,
    Col,
    Card,
    AbnormalForm,
    NormalForm,
    Modal,
    RadioGroup,
    Radio,
    Authc
  },
  data() {
    return {
      namespace: namespace,
      searchModule: {
        actualClearDate: "",
        merchantCode: "",
        payChannel: "ums",
      },
      searchBtnText: "对账",
      disabledSearchBtn: true,
      isNormal: true,
      exportDateType: "date",
      showCollectExport: false,
      exportDate: "",
      tenants: [],
      channels: [
        { value: "银联渠道", key: "ums" },
        { value: "招总行渠道", key: "cmb" },
        { value: "富滇渠道", key: "fudian" },
      ],
      report: [],
      diffCauseList: [],
      settleSummary: {}, // 对账结果
      iconStyle: {
        type: "#19be6b",
        color: "md-checkmark-circle",
      },
    };
  },
    beforeMount: async function() {
    let id = this.$route.query.id;
    console.log('beforeMount:',this.$route.query)
    this.searchModule={...this.searchModule,...this.$route.query}

  },

  methods: {
    // 查询数据
    async handleAccountChecking() {
      await this.querySettleSummaryOne(this.searchModule);
      // 根据返回结果改变图标样式
      if (this.isNormal) {
        this.iconStyle = { color: "#19be6b", type: "md-checkmark-circle" };
      } else {
        this.iconStyle = { color: "#ed4014", type: "md-close-circle" };
      }
    },
    // 查询差异备注
    async getDiffCauseList() {
      let res = await this.$store.dispatch(`${namespace}/getDiffCauseList`);
      if (res.data.ret === 0) {
        let data = res.data.data;
        this.diffCauseList = data || [];
      } else {
        this.diffCauseList = [];
      }
    },
    handleChange() {
      if (
        this.searchModule.actualClearDate != "" &&
        this.searchModule.merchantCode != "" &&
        this.searchModule.payChannel != ""
      ) {
        this.disabledSearchBtn = false;
      } else {
        this.disabledSearchBtn = true;
      }
    },
    // 更新对账
    async doReSettle() {
      if (!this.isNormal && this.settleSummary && this.settleSummary.id) {
        let self = this;
        Modal.confirm({
          title: "确定重新对账？",
          content:
            "对账功能非常耗服务器性能，请避免工作时间操作，以免影响线上其他业务！",
          okText: "确定",
          cancelText: "取消",
          onOk: async () => {
            let res = await self.$store.dispatch(
              `${namespace}/doReSettle`,
              self.searchModule
            );
            if (res.data.ret === 0) {
              this.$Message.success({
                content: "更新对账成功！",
              });
              self.querySettleSummaryOne(this.searchModule);
            } else {
              this.$Message.error({
                content: res.data.msg || "更新对账异常！",
              });
            }
          },
        });
      }
    },
    async querySettleSummaryOne(params) {
      try {
        params.actualClearDate = util.formatDate(
          this.searchModule.actualClearDate
        );
        let res = await this.$store.dispatch(
          `${namespace}/querySettleSummaryOne`,
          params
        );
        if (res.data.ret === 0) {
          let data = res.data.data;
          this.settleSummary = data || {};
          if (!data || data.check_result === 1) {
            this.isNormal = true;
          } else {
            this.isNormal = false;
          }
        } else {
          this.settleSummary = {};
          this.$Message.error({
            content: res.data.msg || "查询异常！",
          });
        }
      } catch (error) {
        this.$Message.error({
          content: error,
        });
      }
    },
    resetForm() {},

    // 汇总导出
    handleShowCollectExport() {
      this.showCollectExport = true;
    },
    async exportOne() {
      if (!this.disabledSearchBtn) {
        const merchant = this.tenants.filter(
          (item) => item.value === this.searchModule.merchantCode
        );
        const merchantName = merchant ? merchant[0].label : "商户";
        const dateStr = util.formatDate(this.searchModule.actualClearDate);
        const res = await this.$store.dispatch(
          `${namespace}/exportOne`,
          this.searchModule
        );
        if (res) {
          util.exportExcle(res, `${merchantName}${dateStr}对账单汇总`);
        }
      }
    },
    async collectExport() {
      console.log("导出成功");
      if (!this.exportDate) {
        this.$Message.error({
          content: "请选择导出条件",
        });
        return;
      }
      let params = {
        startDate: util.formatDate(this.exportDate),
        endDate: util.formatDate(this.exportDate),
      };
      if (this.exportDateType === "month") {
        //整月
        params.startDate = util.formatMonth(this.exportDate) + "-01";
        params.endDate = util.formatMonth(this.exportDate) + "-31";
      }
      const res = await this.$store.dispatch(`${namespace}/exportAll`, params);
      if (res) {
        util.exportExcle(
          res,
          `${params.startDate}至${params.endDate}对账单汇总表`
        );
      }
    },

    async initSettleDate() {
      if(!this.searchModule.actualClearDate){
        const date = new Date(new Date()-24*60*60*1000);
        const now = date.toLocaleDateString();
        this.searchModule.actualClearDate = now;
      }

      await this.queryMerchant();
      await this.getDiffCauseList();
      await this.handleAccountChecking()
      this.handleChange()
    },
    async queryMerchant() {
      try {
        let res = await this.$store.dispatch(
          `${namespace}/getMerchandList`,
          {}
        );
        if (res.data.ret === 0) {
          let data = res.data.data;
          this.tenants = data.length
            ? data.map(({ merchantName, merchantCode }) => {
                return {
                  label: merchantName,
                  value: merchantCode,
                };
              })
            : [];
        }
      } catch (error) {
        this.$Message.error({
          content: error,
        });
      }
    },
  },
  created() {
    this.initSettleDate();
  },
};
</script>

<style scoped>
.form >>> .ivu-col {
  line-height: 60px;
}
.card {
  margin-top: 15px;
}
</style>
